package com.sicheng.algorithm.string;

/**
 * @author zsc
 * @version 1.0
 * @date 2021/9/16 17:30
 */
public class StringToInt {
    /**
     * 将一个字符串转换成一个整数，
     * 字符串不是一个合法的数值则返回 0，要求不能使用字符串转换整数的库函数。
     * Iuput:
     * +2147483647
     * 1a33
     * <p>
     * Output:
     * 2147483647
     * 0
     */
    public static void main(String[] args) {
        System.out.println(stringToInt("-1a3455"));
    }


    public static int stringToInt(String numberString) {
        if (numberString == null || numberString.length() == 0)
            return 0;

        char symbol = numberString.charAt(0);//符号位
        boolean isLegal = symbol == '-' || symbol == '+';

        if (!isLegal)
            return 0;

        int num = 0;
        if (numberString.length() >= 2) {
            for (int i = 1; i < numberString.length(); i++) {
                char current = numberString.charAt(i);
                if (current > '9' || current < '0')
                    return 0;
                num = num * 10 + (current - '0');
            }
        }

        if (symbol == '+')
            return num;

        return -num;

    }
}
